package org.project.single.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import org.project.single.exception.SystemCodeException;
import org.project.single.mapper.SysMenuMapper;
import org.project.single.pojo.constant.CacheNameConst;
import org.project.single.pojo.po.SysMenu;
import org.project.single.pojo.ro.EnableRo;
import org.project.single.pojo.ro.menu.EditMenuBackRo;
import org.project.single.pojo.ro.menu.MenuListBackRo;
import org.project.single.pojo.systemEnum.SystemCodeEnum;
import org.project.single.pojo.vo.menu.MenuDetailBackVo;
import org.project.single.pojo.vo.menu.MenuListBackVo;
import org.project.single.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    @Transactional
    public void editMenuBack(EditMenuBackRo editMenuBackRo) {
        SysMenu sysMenu = BeanUtil.copyProperties(editMenuBackRo, SysMenu.class);
        if (ObjectUtil.isNull(sysMenu.getId())){
            sysMenu.setId(IdUtil.getSnowflake().nextIdStr());
            sysMenu.setCode(IdUtil.getSnowflake().nextIdStr());
            sysMenu.setEnableFlag(0);
            sysMenu.setDelFlag(0);
            sysMenuMapper.insert(sysMenu);
        }else {
            sysMenuMapper.updateById(sysMenu);
        }
    }

    @Override
    public List<MenuListBackVo> getMenuListBack(MenuListBackRo menuListBackRo) {
        return sysMenuMapper.getMenuListBack(menuListBackRo);
    }

    @Override
    public MenuDetailBackVo getDetailBack(String id) {
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        if (ObjectUtil.isNull(sysMenu)){
            MenuDetailBackVo menuDetailBackVo = BeanUtil.copyProperties(sysMenu, MenuDetailBackVo.class);
            return menuDetailBackVo;
        }
        throw new SystemCodeException(SystemCodeEnum.DATA_ERR);
    }

    @Override
    @Transactional
    public void deleteMenuBack(String id) {
        SysMenu sysMenu = sysMenuMapper.selectById(id);
        if (ObjectUtil.isNotNull(sysMenu)){
            String cacheKey = CacheNameConst.RBAC_ROLE_CACHE_DATA+sysMenu.getCode();
            sysMenuMapper.deleteById(id);
        }
    }

    @Override
    @Transactional
    public void enableMenu(EnableRo enableRo) {
        SysMenu data = sysMenuMapper.selectById(enableRo.getId());
        if (ObjectUtil.isNotNull(data)){
            SysMenu sysMenu = BeanUtil.copyProperties(enableRo, SysMenu.class);
            sysMenuMapper.updateById(sysMenu);
        }
    }
}
